package zunge.pmp2;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

import zunge.tools.DbConn;

public class PmpChangeAnalyzer {
	
	public static final long TIME_CHANGE = 1800;

	public static void main(String[] args){
		String ptn="";
		try{
			DbConn connIn = new DbConn("127.0.0.1", "pmp2","root","sergeypk428571");
			DbConn connOut = new DbConn("127.0.0.1", "pmp2","root","sergeypk428571");
			
			ResultSet rs = connIn.executeQueryInStream(
					"select u_id, a_id, f_id, r_count, r_final, r_change, records from stat_changes");
			int r_change;String records;
			
			int f_id, preP,curP;long preT,curT;int swift; int baf;
			
			PreparedStatement psptn = connOut.getPreparedStatement("insert into stat_changes_pattern "
					+ "(u_id, a_id, f_id, rc_baf, rc_swift, rc_pattern) values (?, ?, ?, ?, ?, ?)");
			PreparedStatement psswf = connOut.getPreparedStatement("insert into stat_changes_swift "
					+ "(u_id, a_id, f_id, r_pre, r_cur, t_delta) values (?, ?, ?, ?, ?, ?)");
			
			while(rs.next()){
				r_change = rs.getInt(6);
				if(r_change==1){
					
					f_id = rs.getInt(3);
					records = rs.getString(7);
					String[] frags = records.split(",");
					preP = -1;preT = -1;ptn = "";swift = 0;baf = 0;
					
					for(String frag:frags){
						String[] fields = frag.split(":");
						
						curT = Long.parseLong(fields[0]);
						curP = Integer.parseInt(fields[1]);
						if(f_id!=1 && f_id!=6 && curP==1){curP=2;} //If not location/contact, fake=reject.
						
						if(preP == -1){
							ptn += curP;
							preT = curT;
							preP = curP;
						}else if(preP != curP){
							if(curT - preT >= TIME_CHANGE){//recognized change
								ptn += curP;
								preT = curT;
								preP = curP;
							}else{//swift change, not recognized.
								swift += 1;
								psswf.setInt(1, rs.getInt(1));
								psswf.setInt(2, rs.getInt(2));
								psswf.setInt(3, rs.getInt(3));
								psswf.setInt(4, preP);
								psswf.setInt(5, curP);
								psswf.setLong(6, curT - preT);
								connOut.executeUpdate(psswf);
								
								if(ptn.length()>1){
									ptn = ptn.substring(0,ptn.length()-1);
								}else{
									ptn = ""+curP;
								}
								preP = curP;
								preT = curT;
							}
						}
					}
					if(ptn.length()>=5){
						baf = 1;
						if(ptn.length()>10){ptn=ptn.substring(ptn.length()-10, ptn.length());}
					}
					psptn.setInt(1, rs.getInt(1));
					psptn.setInt(2, rs.getInt(2));
					psptn.setInt(3, rs.getInt(3));
					psptn.setInt(4, baf);
					psptn.setInt(5, swift);
					psptn.setString(6, ptn);
					connOut.executeUpdate(psptn);
				}
			}
			rs.close();
			
		}catch(Exception e){
			System.err.println(ptn);
			e.printStackTrace();
		}
	}
	
	//LOL

}
